﻿using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class PlayerScript : MonoBehaviour {

    public float playerVelocity;
    private Vector3 playerPosition;             
    public float boundary;                                                          //游戏的边界限制

    public int level;                                                               //游戏关卡
    private int score;                                                              //游戏得分
    private int lives;                                                              //玩家生命数

    public AudioClip soundForScore;
    public AudioClip soundForLife;

    private GUIStyle fontStyle;                                                     //字体风格
    private AudioSource audioComponent;

    // Use this for initialization
    void Start () {

        playerPosition = gameObject.transform.position;

        score = 0;
        lives = 3;
        fontStyle = new GUIStyle();
        fontStyle.normal.background = null;
        fontStyle.normal.textColor = new Color(1, 0, 0);
        fontStyle.fontSize = 30;

        audioComponent = (AudioSource)GetComponent<AudioSource>();
	}
	
	// Update is called once per frame
	void Update () {
        //horizontal
        playerPosition.x += playerVelocity * Input.GetAxis("Horizontal");                           //水平方向的移动分量乘以玩家的移动速度

        //玩家按下了ESC按键的消息响应
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }

        //边界控制
        if (playerPosition.x > boundary)
        {
            playerPosition.x = boundary;
        }
        else if (playerPosition.x < -boundary)
        {
            playerPosition.x = -boundary;
        }

        transform.position = playerPosition;

        JudgeLose();                                            //判断玩家的闯关情况
    }


    void addScore(int s)
    {
        score += s;
        audioComponent.PlayOneShot(soundForScore);
    }
    void takeLife()
    {
        lives--;
        audioComponent.PlayOneShot(soundForLife);
    }
    void JudgeLose()
    {
        if (this.lives <= 0)
        {
            SceneManager.LoadScene("Level1");
        }
        if (GameObject.FindGameObjectsWithTag("Block").Length <= 0)
        {
            if (Application.loadedLevelName == "Level1")
            {
                SceneManager.LoadScene("Level2");
            }
            else
            {
                Application.Quit();
            }
        }
    }

    void OnGUI()
    {
        GUI.Label(new Rect(5.0f,5.0f,200.0f,200.0f),"关卡：" + level + "   分数：" + score + "  生命：" + lives, fontStyle);
    }
}
